package com.example.demo.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

public class FileUtils {

    public static String readFileToString(String filePath) throws IOException {
        StringBuilder sb = new StringBuilder();

        FileReader fileReader = new FileReader(filePath);
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        String line;
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
            sb.append("\n");
        }
        bufferedReader.close();
        return sb.toString();
    }

    public static void writeFileToString(String filePath,String content)  {
        try {
            FileWriter writer = new FileWriter(filePath);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void downloadFile(String filename, HttpServletResponse response){
        File dir = new File("uploadFile");
        File file = new File(dir.getAbsolutePath() + File.separator + filename);
        response.setHeader("content-type","application/octet-stream");
        response.setContentType("application/octet-stream");
        try {
            response.setHeader("Content-Disposition","attachment;filename="+java.net.URLEncoder.encode(filename,"UTF-8"));
        } catch (UnsupportedEncodingException e) {
        }
        byte[] buff = new byte[1024];
        FileInputStream bis = null;
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            bis = new FileInputStream(file);
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e2){
            e2.printStackTrace();
        } finally {
            if(bis != null){
                try{
                    bis.close();
                    //os.close();
                } catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

}
